package com.yztc.orangeentertainment.ui.main.channalcontentfragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.yztc.orangeentertainment.R;
import com.yztc.orangeentertainment.adapter.BaseRecyclerAdapter;
import com.yztc.orangeentertainment.adapter.ChannelContentAdapter;
import com.yztc.orangeentertainment.adapter.MyChannelPageAdapter;
import com.yztc.orangeentertainment.base.BaseFragment;
import com.yztc.orangeentertainment.bean.channalbean.InfoBean;
import com.yztc.orangeentertainment.bean.channalbean.ListBean;
import com.yztc.orangeentertainment.ui.main.channalarticle.ChannalArticleActivity;
import com.yztc.orangeentertainment.utils.DividerItemDecoration;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * Created by My on 2016/10/5.
 */
public class ChannalContentFragment extends BaseFragment implements ChannalContentContact.View {

    @InjectView(R.id.vp_channalhead)
    ViewPager vpChannalhead;
    @InjectView(R.id.tv_channalheadicon)
    TextView tvChannalheadicon;
    @InjectView(R.id.tv_channalheadtitle)
    TextView tvChannalheadtitle;
    @InjectView(R.id.ll_channalhead)
    LinearLayout llChannalhead;
    private RecyclerView rvChannalcontent;
    private int currentItem=0;//定义vpChannalhead的当前轮播的位置
    private int page=1;        //默认加载第一页
    private TextView tvYanse;
    private SwipeRefreshLayout swipeRefreshLayout;
    private View head;
    private int id;
    private ImageView[] icons;
    private ArrayList<ListBean> totalList=new ArrayList<>();
    private int mDistanceY;
    private LinearLayoutManager linearLayoutManager;
    private MyChannelPageAdapter adapter1;
    private int lastVisibleItem;
    private List<ImageView> images = new ArrayList<>();
    private ChannalContentContact.Presenter presenter;
    private ChannelContentAdapter adapter;
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:
                    //实现viewpager的无限轮播
                    if(vpChannalhead!=null){
                        vpChannalhead.setCurrentItem(currentItem);
                    }
                    break;
            }
        }
    };
    @Override
    public int getLayoutId() {
        return R.layout.channal_content;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        initView(rootView);
        initHeadView();
        Bundle bundle = getArguments();
        id = bundle.getInt("id", 0);
        currentItem=0;
        initData();
        //swipeRefreshLayout设置setOnRefreshListener实现页面的下拉刷新
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        initData();
                        adapter1.notifyDataSetChanged();
                        adapter.notifyDataSetChanged();
                        swipeRefreshLayout.setRefreshing(false);
                    }
                }, 2000);
            }
        });
        //rvChannalcontent根据上拉到页面的最低端来加载下一页
        rvChannalcontent.addOnScrollListener(new RecyclerView.OnScrollListener(){
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                //当滑动到页面的最底端的时候最后一个item的下标+1等于adapter数据的个数，加载下一页
                if(newState == RecyclerView.SCROLL_STATE_IDLE && (lastVisibleItem + 1) ==adapter
                        .getItemCount()){
                    page++;
                    swipeRefreshLayout.setRefreshing(true);
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            swipeRefreshLayout.setRefreshing(true);
                            initData();
                            adapter.notifyDataSetChanged();
                            swipeRefreshLayout.setRefreshing(false);
                        }
                    } , 2000);
                }
            }
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
            }
        });
        return rootView;
    }
    //实例化presenter来连接model层获取网络数据
    private void initData() {
        presenter = new ChannalContentPresenter(this);
        presenter.getChannalContentFromNet(getActivity(), id,page);

    }

    /**
     * 实例化
     * @param rootView
     *
     */
    private void initView(View rootView) {
        vpChannalhead= (ViewPager) rootView.findViewById(R.id.vp_channalhead);
        tvYanse = (TextView) rootView.findViewById(R.id.tv_yanse);
        rvChannalcontent = (RecyclerView) rootView.findViewById(R.id.rv_channalcontent);
        swipeRefreshLayout= (SwipeRefreshLayout) rootView.findViewById(R.id.srfl_channalcontent);
         linearLayoutManager = new LinearLayoutManager(getActivity());
        //水平摆放
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        //间距
        rvChannalcontent.addItemDecoration(new DividerItemDecoration(10));
        rvChannalcontent.setLayoutManager(linearLayoutManager);
        rvChannalcontent.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                //滑动的距离
                mDistanceY += dy;
                //toolbar的高度
                int toolbarHeight = vpChannalhead.getBottom();

                //当滑动的距离 <= toolbar高度的时候，改变Toolbar背景色的透明度，达到渐变的效果
                if (mDistanceY <= toolbarHeight) {
                    float scale = (float) mDistanceY / toolbarHeight;
                    float alpha = scale * 255;
                    tvYanse.setBackgroundColor(Color.argb((int) alpha, 128, 0, 0));
                } else {
                    //上述虽然判断了滑动距离与toolbar高度相等的情况，但是实际测试时发现，标题栏的背景色
                    //很少能达到完全不透明的情况，所以这里又判断了滑动距离大于toolbar高度的情况，
                    //将标题栏的颜色设置为完全不透明状态
                    tvYanse.setBackgroundResource(R.color.darkorange);
                }
            }
        });
        swipeRefreshLayout.setProgressBackgroundColorSchemeResource(android.R.color.white);
        swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_light,
                android.R.color.holo_red_light, android.R.color.holo_orange_light,
                android.R.color.holo_green_light);
        swipeRefreshLayout.setProgressViewOffset(false, 0, (int) TypedValue
                .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50, getResources()
                        .getDisplayMetrics()));


    }
    //实例化头部view视图的空间
    private void initHeadView() {

        head = LayoutInflater.from(getActivity()).inflate(R.layout.channal_content_head,
                rvChannalcontent,
                false);
        ButterKnife.inject(this, head);
    }
    //获取ViewPager数据成功
    @Override
    public void onChannalContentViewPageSucess(final List<InfoBean> infoBeanList) {
        if(llChannalhead!=null) {
            llChannalhead.removeAllViewsInLayout();
            images=new ArrayList<>();
            if (infoBeanList.size() == 1) {
                ImageView iv = new ImageView(getActivity());
                iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
                Glide.with(getActivity()).load(infoBeanList.get(0).getPic()).into(iv);
                iv.setColorFilter(0x40000000);
                iv.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.MATCH_PARENT));
                images.add(iv);
                iv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(getActivity(), ChannalArticleActivity.class);
                        intent.putExtra("id", infoBeanList.get(0).getId() + "");
                        startActivity(intent);
                    }
                });
                if (infoBeanList.get(0).getTitle() != null && infoBeanList.get(0).getCat() != null &&
                        tvChannalheadicon != null) {
                    tvChannalheadicon.setText(infoBeanList.get(0).getCat().getName());
                    tvChannalheadtitle.setText(infoBeanList.get(0).getTitle());
                }
                adapter1 = new MyChannelPageAdapter(images);
                vpChannalhead.setAdapter(adapter1);
            } else {
                icons = new ImageView[infoBeanList.size()];
                for (int i = 0; i < infoBeanList.size(); i++) {
                    icons[i] = new ImageView(getActivity());
                    icons[i].setImageResource(R.mipmap.dot_light);
                    icons[i].setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                            ViewGroup.LayoutParams.WRAP_CONTENT));
                    icons[i].setMaxHeight(20);
                    icons[i].setPadding(3, 0, 3, 0);
                    icons[i].setAdjustViewBounds(true);
                    llChannalhead.addView(icons[i]);
                    ImageView iv = new ImageView(getActivity());
                    iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
                    Glide.with(getActivity()).load(infoBeanList.get(i).getPic()).into(iv);
                    iv.setColorFilter(0x40000000);
                    iv.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                            ViewGroup.LayoutParams.MATCH_PARENT));
                    final int finalI = i;
                    iv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(getActivity(), ChannalArticleActivity.class);
                            intent.putExtra("id", infoBeanList.get(finalI).getId() + "");
                            startActivity(intent);
                        }
                    });
                    images.add(iv);
                }
                if (infoBeanList.get(0).getCat() != null && !infoBeanList.get(0).getCat().equals("")) {
                    tvChannalheadicon.setText(infoBeanList.get(0).getCat().getName());
                }
                tvChannalheadtitle.setText(infoBeanList.get(0).getTitle());
                icons[0].setImageResource(R.mipmap.dot_red);
                new Thread(new Runnable() {
                    public void run() {
                        while (true) {
                            try {
                                Thread.sleep(2000);
                                currentItem = (currentItem + 1) % images.size();
                                handler.sendEmptyMessage(1);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }).start();
                adapter1 = new MyChannelPageAdapter(images);
                vpChannalhead.setAdapter(adapter1);
            }

            final List<InfoBean> infoBeanList1 = infoBeanList;
            vpChannalhead.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                }

                @Override
                public void onPageSelected(int position) {
                    if (infoBeanList1.size() != 1) {

                        for (int i = 0; i < infoBeanList1.size(); i++) {
                            icons[i].setImageResource(R.mipmap.dot_light);
                        }
                        if (position < infoBeanList.size()) {
                            icons[position].setImageResource(R.mipmap.dot_red);
                        }
                    }
                    if (position < infoBeanList.size() && infoBeanList.get(position).getCat() != null &&
                            !infoBeanList.get(position).getCat().equals("")) {
                        tvChannalheadicon.setText(infoBeanList.get(position).getCat().getName());
                        currentItem = position;
                        tvChannalheadtitle.setText(infoBeanList.get(position).getTitle());
                    }
                }

                @Override
                public void onPageScrollStateChanged(int state) {

                }
            });


        }
    }
    //获取viewpager数据失败
    @Override
    public void onChannalContentViewPageFaild(String msg) {
        Toast.makeText(getActivity(),msg,Toast.LENGTH_LONG).show();
    }
    //获取recyclerView中的数据成功
    @Override
    public void setChannalContentRVSuccess(final ArrayList<ListBean> listBeen) {
        totalList.addAll(listBeen);
        adapter = new ChannelContentAdapter(getActivity());
        setHeader(rvChannalcontent);
        adapter.addDatas(totalList);
        if(page==1) {
            rvChannalcontent.setAdapter(adapter);
        }else{
            adapter.notifyDataSetChanged();
        }
        adapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, Object data) {
                Intent intent=new Intent(getActivity(), ChannalArticleActivity.class);
                intent.putExtra("id",totalList.get(position).getId()+"");
                intent.putExtra("readnum",totalList.get(position).getReplynum()+"");
                if(totalList.get(position).getCat()!=null&&totalList.get(position).getType()==0) {
                    intent.putExtra("iconimage", totalList.get(position).getCat().getIcon());
                    startActivity(intent);
                }
            }
        });
    }

    //给recyclerView设置头部视图
    private void setHeader(RecyclerView view) {
        adapter.setHeaderView(head);
    }
    //获取recyclerView中的数据失败
    @Override
    public void onChannalContentRVFaild(String msg) {
        Toast.makeText(getActivity(),msg,Toast.LENGTH_LONG).show();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }
}
